<script setup lang="ts">
import { ref, reactive, toRefs, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import type {
  FormInstance,
  FormRules,
  UploadProps,
  UploadUserFile,
} from "element-plus";
import {
  modifyStudentApi,
  queryStudentApi,
  delStudentApi,
  getStudentInfoApi,
  delStudentByMoreApi,
  updateStudentClassIdApi,
  checkStudentPhoneApi,
  uploadExcelStudentURI,
} from "@/http/Api/teachers/studentManageApi";
import { classStatusDataApi } from "@/http/Api/teachers/classManageApi";
import { Refresh } from "@element-plus/icons-vue";

const title = ref("新增学生");

// 搜索部分
const searchFormRef = ref<FormInstance>();
const searchCondition = reactive({
  baiJieClassId: "",
  phone: "",
  username: "",
});
const onSearchSubmit = async () => {
  dataListConfig.baiJieClassId = searchCondition.baiJieClassId;
  dataListConfig.phone = searchCondition.phone;
  dataListConfig.username = searchCondition.username;
  currentPage.value = 1;

  try {
    const res = await queryStudentApi({
      baiJieClassId: searchCondition.baiJieClassId,
      number: 1,
      phone: searchCondition.phone,
      size: pageSize.value,
      username: searchCondition.username,
    });
    console.log("学生请求：", res.data);
    if (res.data.code == "200") {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      ElMessage.error(res.data.msg);
    }
  } catch (err) {
    console.log("搜索失败:", err);
    ElMessage.error("服务器出错");
  }
};
const resetSearchForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 导入上传
const importFileList = ref<UploadUserFile[]>([]);
const onImportBeforeUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log(" - onImportBeforeUpload - ", rawFile);
};
const onMoreFiles: UploadProps["onExceed"] = (files) => {
  console.log(files);
  if (files.length > 5) {
    ElMessage({
      message: "最多支持上传5个文件！",
      type: "error",
    });
  }
};
const onImportSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile,
  uploadFiles
) => {
  console.log(" - onImportSuccess - ", response);
  if (response.code === "200") {
    importFileList.value = [];

    ElMessage({
      message: "数据导入成功！",
      type: "success",
    });
  } else {
    importFileList.value = [];

    ElMessage({
      message: "数据导入失败，请联系管理员！",
      type: "error",
    });
  }
};
const onImportError: UploadProps["onError"] = (
  error,
  uploadFile,
  uploadFiles
) => {
  console.log(" - onImportError - ", error, uploadFile, uploadFiles);
  importFileList.value = [];
  ElMessage({
    message: "数据导入失败，请联系管理员！",
    type: "error",
  });
};

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  currentPage.value = val;
  getInitData();
};

// 学生信息
const dataListConfig = reactive({
  baiJieClassId: "",
  phone: "",
  username: "",
});
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const selectionTableData = ref<Array<string>>([]); //被选中的学生
const tableData = ref([]);
const total = ref(0);
const modalState = ref("ADD");
const dataFormRef = ref<FormInstance>();
const classData = ref<Array<any>>([]); // 可用班级信息

const state = reactive({
  // 当前学生信息
  modalForm: {
    id: "",
    headPortrait: "",
    nickname: "",
    phone: "",
    sex: "",
    baiJieClassId: "",
    username: "",
  },
  // baiJieClass: [
  //   // 百杰班级
  //   {
  //     baiJieClassId: 1,
  //     baiJieName: "w288",
  //   },
  //   {
  //     baiJieClassId: 13,
  //     baiJieName: "J309",
  //   },
  // ],
});
const { modalForm } = toRefs(state);

// 自定义手机号是否存在验证
const validatePhone = async (rule: any, value: any, callback: any) => {
  const res = await checkStudentPhoneApi(value);
  console.log("验证手机号是否已经注册:", res.data);

  if (res.data.data == 1) {
    callback(new Error("手机号码已经注册！"));
  } else {
    callback();
  }
};
// 学生信息验证
const modalRules = reactive({
  username: [
    { required: true, message: "请输入学生名字", trigger: "blur" },
    { min: 2, max: 10, message: "长度应该在 2 到 10之间", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入联系方式", trigger: "blur" },
    { min: 11, max: 11, message: "手机号码长度不正确", trigger: "blur" },
    { validator: validatePhone, trigger: "blur" },
  ],
  sex: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  baiJieClassId: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
});

// 列表请求
async function getInitData() {
  try {
    const res = await queryStudentApi({
      baiJieClassId: dataListConfig.baiJieClassId,
      number: currentPage.value,
      phone: dataListConfig.phone,
      size: pageSize.value,
      username: dataListConfig.username,
    });
    console.log("学生请求：", res.data);
    if (res.data.code == "200") {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      ElMessage.error(res.data.msg);
    }

    const classRes = await classStatusDataApi(1);
    console.log("获取可用班级", classRes.data);

    if (classRes.data.code == "200") {
      classData.value = classRes.data.data;
    } else {
      ElMessage.error(classRes.data.msg);
    }
  } catch (err) {
    console.log("学生请求失败：", err);
    ElMessage.error("请求失败，请稍后重试!");
  }
}
onMounted(() => {
  getInitData();
});
// 刷新数据
const refreshClassData = () => {
  modalState.value = "ADD";
  currentPage.value = 1;
  getInitData();
};

// 数据编辑模态框
const studentDialogVisible = ref(false);
const onCloseDialog = () => {
  console.log("关闭模态框");
  dataFormRef.value!.resetFields();
};
// 打开新增模态框
const onOpenAddstudentDialog = () => {
  studentDialogVisible.value = true;
  modalState.value = "ADD";
  title.value = "新增学生";
};

// 提交数据
const submitModalForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (!valid) return console.log("error submit!", fields);

    console.log("submit - " + modalState.value, modalForm);

    try {
      const res = await modifyStudentApi(modalForm.value);

      console.log("学生修改结果：", res.data);

      if (res.data.code == "200") {
        studentDialogVisible.value = false;

        ElMessage({
          type: "success",
          message: res.data.msg,
        });
      } else {
        ElMessage.error(res.data.msg);
      }
    } catch (err) {
      console.log("学生请求失败：", err);
      ElMessage.error("请求失败，请稍后重试!");
    }
  });
};

// 查看学生信息
const onViewSingle = (row: any) => {
  console.log(row);
  modalState.value = "VIEW";
  title.value = "查看学生";
  getStudentInfoApi(row.phone)
    .then((res) => {
      console.log("查看信息：", res.data);
      modalForm.value = res.data.data;
    })
    .catch((err) => {
      console.log("查看信息失败：", err);
    });
  studentDialogVisible.value = true;
};

// 删除学生数据
const onDelSingle = async (row: any) => {
  ElMessageBox.confirm("确认删除该条信息吗?", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        console.log(row);
        const res = await delStudentApi(row.phone);
        console.log("删除数据结果：", res.data);

        if (res.data.code == "200") {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getInitData();
        } else {
          ElMessage.error(res.data.msg);
        }
      } catch (err) {
        console.log("删除请求失败：", err);
        ElMessage.error("请求失败，请稍后重试!");
      }
    })
    .catch(() => {
      console.log("取消删除");
    });
};
// 批量删除学生
const onDelMoreData = () => {
  if (selectionTableData.value.length == 0) {
    return ElMessage({
      type: "warning",
      message: "请先选择要操作的数据",
    });
  }

  ElMessageBox.confirm("确认删除这些信息吗?", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await delStudentByMoreApi(selectionTableData.value);
        console.log("删除数据结果：", res.data);
        if (res.data.code == "200") {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getInitData();
        } else {
          ElMessage.error(res.data.msg);
        }
      } catch (err) {
        console.log("删除请求失败：", err);
        ElMessage.error("请求失败，请稍后重试!");
      }
    })
    .catch(() => {
      console.log("取消删除");
    });
};
// 表格选中状态数据保存
const selectionChange = (selection: [any]) => {
  selectionTableData.value = selection.map((item) => item.phone);
  console.log(selection, selectionTableData.value);
};

// 编辑学生信息
const onEdit = (row: any) => {
  console.log(row);
  modalState.value = "EDIT";
  title.value = "编辑学生";
  getStudentInfoApi(row.phone)
    .then((res) => {
      console.log("查看信息：", res.data);
      modalForm.value = res.data.data;
    })
    .catch((err) => {
      console.log("获取信息失败：", err);
    });
  studentDialogVisible.value = true;
};

// 批量编辑学生班级信息
const onUpdateStudentClassId = () => {
  console.log("批量编辑学生班级信息");
  if (selectionTableData.value.length == 0) {
    return ElMessage({
      type: "warning",
      message: "请先选择要操作的数据",
    });
  }
  moreDialogVisible.value = true;
};

// 批量编辑
const dataMoreFormRef = ref<FormInstance>();
const moreDialogVisible = ref(false);
const modalMoreForm = reactive({
  baiJieClassId: "",
});
const modalMoreRules = reactive({
  baiJieClassId: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
});
// 批量编辑提交
const submitMoreModalForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (!valid) return console.log("error submit!", fields);

    try {
      const res = await updateStudentClassIdApi({
        phoneArr: selectionTableData.value,
        baiJieClassId: modalMoreForm.baiJieClassId,
      });

      console.log("学生修改结果：", res.data);

      if (res.data.code == "200") {
        moreDialogVisible.value = false;

        ElMessage({
          type: "success",
          message: res.data.msg,
        });
      } else {
        ElMessage.error(res.data.msg);
      }
    } catch (err) {
      console.log("学生请求失败：", err);
      ElMessage.error("请求失败，请稍后重试!");
    }
  });
};

// 表单重置
const resetModalForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<template>
  <main>
    <div class="page-header">
      <div class="page-title">
        <p>学生管理</p>
      </div>
    </div>
    <div class="page-body">
      <!-- 搜索 -->
      <div class="search">
        <el-form
          ref="searchFormRef"
          :model="searchCondition"
          :inline="true"
          class="demo-form-inline"
        >
          <el-form-item label="学生名字" prop="username">
            <el-input
              size="small"
              v-model="searchCondition.username"
              style="width: 100px"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              size="small"
              v-model="searchCondition.phone"
              style="width: 100px"
            />
          </el-form-item>
          <el-form-item label="班级" prop="baiJieClassId">
            <el-select
              class="m-2"
              size="small"
              v-model="searchCondition.baiJieClassId"
              style="width: 100px"
            >
              <el-option
                v-for="item in classData"
                :key="item.id"
                :label="item.baiJieName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="onSearchSubmit"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              @click="resetSearchForm(searchFormRef)"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <!-- 批量操作 -->
      <div class="batch-processing">
        <div class="batch-processing-left">
          <el-button type="primary" link @click="onOpenAddstudentDialog"
            >新增学生</el-button
          >
          <el-button type="primary" link @click="onDelMoreData"
            >批量删除</el-button
          >
          <el-button type="primary" link @click="onUpdateStudentClassId"
            >批量编辑学生班级</el-button
          >

          <el-upload
            v-model:file-list="importFileList"
            class="upload-demo"
            :action="uploadExcelStudentURI"
            show-file-list
            name="file"
            multiple
            :limit="5"
            accept=".xls"
            :on-success="onImportSuccess"
            :on-error="onImportError"
            :before-upload="onImportBeforeUpload"
            :on-exceed="onMoreFiles"
          >
            <el-button link type="primary">导入学生</el-button>
          </el-upload>
        </div>
        <el-icon class="class_refresh" :size="22" @click="refreshClassData"
          ><Refresh
        /></el-icon>
      </div>

      <!-- 学生列表 -->
      <div class="student-list">
        <el-table
          ref="multipleTableRef"
          :data="tableData"
          @selection-change="selectionChange"
          stripe
          border
          style="width: 100%; min-width: 630px"
        >
          <el-table-column type="selection" width="55" />
          <!-- <el-table-column label="序号" width="54">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column> -->
          <el-table-column prop="id" label="学生id" width="65" />
          <el-table-column prop="username" label="学生姓名" width="85" />
          <el-table-column prop="baiJieName" label="班级名称" width="82" />
          <el-table-column prop="phone" label="联系方式" width="120" />
          <el-table-column prop="sex" label="性别" width="55" />
          <el-table-column
            prop="lastLoginTime"
            label="最后登录系统时间"
            width="140"
          >
            <template #default="scope">
              {{ new Date(scope.row.lastLoginTime).toLocaleDateString() }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button link size="small" @click="onViewSingle(scope.row)"
                >查看</el-button
              >
              <el-button
                link
                size="small"
                type="warning"
                @click="onEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                link
                size="small"
                type="danger"
                @click="onDelSingle(scope.row)"
                >删除</el-button
              >
              <!-- <el-button link size="small">导入学员</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <el-pagination
        small
        background
        layout="prev, pager, next"
        :total="total"
        class="mt-4"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="studentDialogVisible"
      :title="title"
      width="60%"
      @close="onCloseDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="modalForm"
        :rules="modalRules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="id">
          <el-input :value="modalForm.id" disabled />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="modalForm.nickname"
            :disabled="modalState == 'VIEW'"
          />
        </el-form-item>
        <el-form-item label="学生姓名" prop="username">
          <el-input
            v-model="modalForm.username"
            :disabled="modalState == 'VIEW'"
          />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
            v-model="modalForm.phone"
            :disabled="modalState == 'VIEW'"
          />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select
            v-model="modalForm.sex"
            placeholder="请选择性别"
            :disabled="modalState == 'VIEW'"
          >
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="百杰班级" prop="baiJieClassId">
          <el-select
            v-model="modalForm.baiJieClassId"
            placeholder="请选择班级"
            :disabled="modalState == 'VIEW'"
          >
            <el-option
              v-for="item in classData"
              :key="item.id"
              :label="item.baiJieName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="头像" prop="baiJieName">
          <el-input :disabled="modalState == 'VIEW'" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer" v-if="modalState != 'VIEW'">
          <el-button type="primary" @click="submitModalForm(dataFormRef)"
            >提交</el-button
          >
          <el-button @click="resetModalForm(dataFormRef)">重置</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 学生班级批量编辑 -->
    <el-dialog v-model="moreDialogVisible" title="批量编辑" width="60%">
      <el-form
        ref="dataMoreFormRef"
        :model="modalMoreForm"
        :rules="modalMoreRules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="百杰班级" prop="baiJieClassId">
          <el-select
            v-model="modalMoreForm.baiJieClassId"
            placeholder="请选择班级"
          >
            <el-option
              v-for="item in classData"
              :key="item.id"
              :label="item.baiJieName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            type="primary"
            @click="submitMoreModalForm(dataMoreFormRef)"
            >提交</el-button
          >
          <el-button @click="resetModalForm(dataMoreFormRef)">重置</el-button>
        </span>
      </template>
    </el-dialog>
  </main>
</template>

<style lang="scss">
@import "@/assets/scss/global.scss";

.student-list {
  padding: 20px 0;
}
.batch-processing {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.batch-processing-left {
  display: flex;
  align-items: flex-start;
  .upload-demo {
    margin-top: -2px;
  }
}
.class_refresh {
  &:hover {
    color: $color-theme;
  }
}
</style>
